package org.szy.core.common.controller;

import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.Render;
import org.noear.solon.validation.annotation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.szy.core.common.entity.R;
import org.szy.core.common.page.QueryPage;
import org.szy.core.common.prop.AppProperties;
import org.szy.core.common.prop.Sm2Properties;

/**
 * web层通用数据处理
 *
 * @author 孙志阳
 * @date 2023-06-13
 * @since 1.0.0
 **/
@Valid
public class BaseController<T> implements Render {

    protected Logger log = LoggerFactory.getLogger(this.getClass());
    @Inject
    private AppProperties appProperties;

    boolean smEnabled = Sm2Properties.enabled;

    @Override
    public void render(Object data, Context ctx) throws Throwable {
        if (data == null) {
            return;
        }
        if (data instanceof String) {
            //普通字符串，直接输出
            ctx.output((String) data);
        } else if (data instanceof ModelAndView) {
            //视图模型，直接渲染
            ModelAndView view = ((ModelAndView) data);
            view.put("app", appProperties);
            if (smEnabled) {
                view.put("smEnable", smEnabled);
            }
            view.view(view.view() + ".html");
            ctx.render(data);
        } else {
            if (data instanceof Throwable) {
                //此处是重点，把异常进行标准化转换
                Throwable err = (Throwable) data;
//                if (!(data instanceof BaseException)) {
//                    err.printStackTrace();
//                }
//                err.printStackTrace();
                log.error(err.getMessage());
                data = R.fail(err.getMessage());
            }
            ctx.render(data);
        }
    }

    /**
     * 获取分页参数
     */
    public QueryPage<T> getPage() {
        return new QueryPage<T>();
    }
}
